//strpbrk_last.cpp
//return a pointer to the last occurence in str1 of any of the characters in str2
//or a NULL pointer if no match
//Compile Command: g++ -Wall -g -o strpbrk_last strpbrk_last.cpp
#include <map>
#include <cstring>
#include <cstdio>
using namespace std;
const char * strpbrk_last(const char * message, const char * charset)
{
  map<char,int> char_map;
  map<char,int>::iterator iter;
  for(unsigned int i = 0; i<strlen(message); i++){ //put into a map container
    char_map[message[i]] = i;
  }

  int last = -1; //last occurence

  for(unsigned int i = 0; i<strlen(charset); i++) { //find in char_map
    iter = char_map.find(charset[i]);
    if(iter != char_map.end() && last < iter->second)
      last = iter->second;
  }
    //traverse map
  for(iter = char_map.begin();iter!=char_map.end();++iter){
    printf("<%c,%d>\t",iter->first,iter->second);
  }
  printf("\n");
  if(last >= 0)
    return message+last;
  else
    return NULL;
}

const char * strpbrk_last_2(const char * message, const char * charset)
{
  map<char,int> char_map;
  map<char,int>::iterator iter;
  for(int i = strlen(message)-1; i>=0; i--){ //put into a map container
    
    pair<char,int> temp(message[i],i);
    char_map.insert(temp);
  }

  int last = -1; //last occurence

  for(unsigned int i = 0; i<strlen(charset); i++) { //find in char_map
    iter = char_map.find(charset[i]);
    if(iter != char_map.end() && last < iter->second)
      last = iter->second;
  }

  //traverse map
  for(iter = char_map.begin();iter!=char_map.end();++iter){
    printf("<%c,%d>\t",iter->first,iter->second);
  }
  if(last >= 0)
    return message+last;
  else
    return NULL;
}
int main(int argc, char *argv[])
{
  char message[] = "hello hoha";
  char charset[] = "iueo";
  strpbrk_last(message,charset);
  const char * ptr = strpbrk_last_2(message, charset);
  if(ptr)
    printf("%c:%s\n",*ptr,ptr);
  else
    fprintf(stderr,"ptr is %p\n",ptr);
  return 0;
}
